package com.net.wanjian.networkhospitalmanager.activity.base;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewCompat;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;

import com.net.wanjian.networkhospitalmanager.R;
import com.net.wanjian.networkhospitalmanager.netstatus.NetChangeObserver;
import com.net.wanjian.networkhospitalmanager.netstatus.NetStateReceiver;
import com.net.wanjian.networkhospitalmanager.netstatus.NetUtils;
import com.zhy.autolayout.AutoLayoutActivity;

import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

import butterknife.ButterKnife;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;

/**
 * Description:activity基类
 * Created by lidongcai on 2017/4/22.
 * Email:  lidongcaiocc@163.com
 */

public abstract class BaseActivity extends AutoLayoutActivity {
    protected String TAG = getClass().getSimpleName();
    private NetChangeObserver mNetChangeObserver = null;
    private List<Activity> activityList = new ArrayList<>();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {

        overridePendingTransition(R.anim.right_in, R.anim.left_out);

        super.onCreate(savedInstanceState);
        activityList.add(this);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            setTranslucentStatusColor(setStatusColor());
        }

        if (getLayoutId() != 0) {
            setContentView(getLayoutId());
        } else {
            throw new IllegalArgumentException("You must return a right contentView layout resource Id");
        }

        mNetChangeObserver = new NetChangeObserver() {
            @Override
            public void onNetConnected(NetUtils.NetType type) {
                super.onNetConnected(type);
                onNetworkConnected(type);
            }

            @Override
            public void onNetDisConnect() {
                super.onNetDisConnect();
                onNetworkDisConnected();
            }
        };

        NetStateReceiver.registerObserver(mNetChangeObserver);

        ButterKnife.bind(this);
        initData();
    }

    /**
     * 退出方法
     */
    public void exit() {
        JPushInterface.setAliasAndTags(this, "", new LinkedHashSet<String>(), new TagAliasCallback() {
            @Override
            public void gotResult(int i, String s, Set<String> set) {

            }
        });

        for (int i = 0; i < activityList.size(); i++) {
            activityList.get(i).finish();
        }
        activityList = null;
    }

    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(R.anim.left_in, R.anim.right_out);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        NetStateReceiver.removeRegisterObserver(mNetChangeObserver);
    }

    protected void openActivity(Class<?> c, Bundle bundle) {
        Intent intent = new Intent(this, c);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        startActivity(intent);
    }

    protected void openActivity(Class<?> c) {
        openActivity(c, null);
    }

    protected void openActivityForResult(Class<?> c, int requestCode) {
        openActivityForResult(c, requestCode, null);
    }

    protected void openActivityForResult(Class<?> c, int requestCode, Bundle bundle) {
        Intent intent = new Intent(this, c);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        startActivityForResult(intent, requestCode);
    }

    protected abstract void initData();

    protected abstract int getLayoutId();

    protected abstract void onNetworkConnected(NetUtils.NetType type);

    protected abstract void onNetworkDisConnected();


    //6.0申请权限
    protected void requestPermission(String[] permissions) {
        requestPermission(0, permissions);
    }

    protected void requestPermission(int requestCode, String[] permissions) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (permissions == null || permissions.length == 0) {
                return;
            }
            List<String> list = new ArrayList<>();
            for (int i = 0; i < permissions.length; i++) {
                if (ContextCompat.checkSelfPermission(this, permissions[i]) != PackageManager.PERMISSION_GRANTED) {
                    list.add(permissions[i]);
                }
            }
            if (list.isEmpty()) {
                onRequestPermissionsResult(requestCode, true);
            } else {
                for (String s : list) {
                    Log.i(TAG, "s=" + s + "===" + shouldShowRequestPermissionRationale(s));
//                    if (shouldShowRequestPermissionRationale(s)){
//
//                    }
                }
                requestPermissions(list.toArray(new String[list.size()]), requestCode);
            }
        } else {
            onRequestPermissionsResult(requestCode, true);
        }
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        boolean isSuccess = true;
        for (int i = 0; i < permissions.length; i++) {
            if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                isSuccess = false;
                break;
            }
        }
        onRequestPermissionsResult(requestCode, isSuccess);
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    protected void onRequestPermissionsResult(int requestCode, boolean isSuccess) {

    }

    protected int setStatusColor() {
        return getResources().getColor(R.color.colorMain);
    }

    protected void setTranslucentStatusColor(int color) {
        Window window = this.getWindow();
        //取消设置透明状态栏,使 ContentView 内容不再覆盖状态栏
        window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);

        //需要设置这个 flag 才能调用 setStatusBarColor 来设置状态栏颜色
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        //设置状态栏颜色
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            window.setStatusBarColor(color);
        }

        ViewGroup mContentView = (ViewGroup) this.findViewById(Window.ID_ANDROID_CONTENT);
        View mChildView = mContentView.getChildAt(0);
        if (mChildView != null) {
            //注意不是设置 ContentView 的 FitsSystemWindows, 而是设置 ContentView 的第一个子 View . 预留出系统 View 的空间.
            ViewCompat.setFitsSystemWindows(mChildView, true);
        }
    }

    protected void setTranslucentStatus(boolean on) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            Window win = getWindow();
            WindowManager.LayoutParams winParams = win.getAttributes();
            final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
            if (on) {
                winParams.flags |= bits;
            } else {
                winParams.flags &= ~bits;
            }
            win.setAttributes(winParams);
        }
    }
}
